<template>
  <div class="monitor-optimization">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="left">
        <h2>性能优化建议</h2>
        <el-tag type="info" class="ml-2">共 {{ total }} 条优化建议</el-tag>
      </div>
      <div class="right">
        <el-button type="primary" @click="handleGenerate">
          <el-icon><Refresh /></el-icon>生成建议
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>导出报告
        </el-button>
      </div>
    </div>

    <!-- 性能概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>系统健康度</span>
            </div>
          </template>
          <div class="health-score">
            <el-progress
              type="dashboard"
              :percentage="overviewData.healthScore"
              :color="getHealthColor"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>性能评分</span>
            </div>
          </template>
          <div class="performance-score">
            <el-progress
              type="dashboard"
              :percentage="overviewData.performanceScore"
              :color="getPerformanceColor"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>资源利用率</span>
            </div>
          </template>
          <div class="resource-usage">
            <el-progress
              type="dashboard"
              :percentage="overviewData.resourceUsage"
              :color="getResourceColor"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>优化效果</span>
            </div>
          </template>
          <div class="optimization-effect">
            <el-progress
              type="dashboard"
              :percentage="overviewData.optimizationEffect"
              :color="getOptimizationColor"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="建议类型">
        <el-select v-model="queryParams.type" placeholder="请选择建议类型" clearable>
          <el-option
            v-for="item in suggestionTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
          <el-option
            v-for="item in priorityLevels"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="item in suggestionStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 建议列表 -->
    <el-table
      v-loading="loading"
      :data="suggestionList"
      border
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="建议类型" prop="type" width="120">
        <template #default="{ row }">
          <el-tag :type="getSuggestionTypeTag(row.type)">
            {{ getSuggestionTypeLabel(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" min-width="200" show-overflow-tooltip />
      <el-table-column label="优先级" prop="priority" width="100">
        <template #default="{ row }">
          <el-tag :type="getPriorityTag(row.priority)">
            {{ getPriorityLabel(row.priority) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="影响范围" prop="scope" width="120" show-overflow-tooltip />
      <el-table-column label="预期效果" prop="expectedEffect" width="120" show-overflow-tooltip />
      <el-table-column label="状态" prop="status" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTag(row.status)">
            {{ getStatusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180" />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleView(row)">
            <el-icon><View /></el-icon>查看
          </el-button>
          <el-button type="success" link @click="handleApply(row)">
            <el-icon><Check /></el-icon>应用
          </el-button>
          <el-button type="warning" link @click="handleTrack(row)">
            <el-icon><Timer /></el-icon>跟踪
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 建议详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="优化建议详情"
      width="800px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="建议类型">
          {{ getSuggestionTypeLabel(currentSuggestion.type) }}
        </el-descriptions-item>
        <el-descriptions-item label="优先级">
          <el-tag :type="getPriorityTag(currentSuggestion.priority)">
            {{ getPriorityLabel(currentSuggestion.priority) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="标题" :span="2">
          {{ currentSuggestion.title }}
        </el-descriptions-item>
        <el-descriptions-item label="问题描述" :span="2">
          {{ currentSuggestion.description }}
        </el-descriptions-item>
        <el-descriptions-item label="影响范围" :span="2">
          {{ currentSuggestion.scope }}
        </el-descriptions-item>
        <el-descriptions-item label="优化方案" :span="2">
          {{ currentSuggestion.solution }}
        </el-descriptions-item>
        <el-descriptions-item label="预期效果" :span="2">
          {{ currentSuggestion.expectedEffect }}
        </el-descriptions-item>
        <el-descriptions-item label="实施步骤" :span="2">
          <el-steps direction="vertical" :active="currentSuggestion.steps.length">
            <el-step
              v-for="(step, index) in currentSuggestion.steps"
              :key="index"
              :title="step.title"
              :description="step.description"
            />
          </el-steps>
        </el-descriptions-item>
        <el-descriptions-item label="风险评估" :span="2">
          {{ currentSuggestion.riskAssessment }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleApply(currentSuggestion)">
            应用建议
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 优化跟踪对话框 -->
    <el-dialog
      v-model="trackDialogVisible"
      title="优化实施跟踪"
      width="1000px"
      append-to-body
    >
      <el-tabs v-model="activeTrackTab">
        <el-tab-pane label="实施进度" name="progress">
          <div class="track-content">
            <el-timeline>
              <el-timeline-item
                v-for="(activity, index) in trackData.activities"
                :key="index"
                :type="activity.type"
                :timestamp="activity.timestamp"
              >
                {{ activity.content }}
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-tab-pane>
        <el-tab-pane label="效果分析" name="effect">
          <div class="track-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="chart-container">
                  <div ref="performanceChartRef" style="width: 100%; height: 300px"></div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="chart-container">
                  <div ref="resourceChartRef" style="width: 100%; height: 300px"></div>
                </div>
              </el-col>
            </el-row>
            <el-table :data="trackData.effectAnalysis" border style="width: 100%; margin-top: 20px">
              <el-table-column label="指标" prop="metric" width="150" />
              <el-table-column label="优化前" prop="before" width="120" />
              <el-table-column label="优化后" prop="after" width="120" />
              <el-table-column label="提升比例" prop="improvement" width="120">
                <template #default="{ row }">
                  <span :class="{ 'text-success': row.improvement > 0, 'text-danger': row.improvement < 0 }">
                    {{ row.improvement }}%
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="说明" prop="description" show-overflow-tooltip />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import {
  Refresh,
  Download,
  Search,
  View,
  Check,
  Timer,
  Delete
} from '@element-plus/icons-vue'
import {
  getPerformanceSuggestions,
  applyPerformanceSuggestion,
  getPerformanceSuggestionDetail,
  getPerformanceSuggestionRecords,
  getPerformanceOptimizationAnalysis,
  getPerformanceOptimizationTrend,
  exportPerformanceOptimizationReport
} from '@/api/message'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: undefined,
  priority: undefined,
  status: undefined
})

// 建议类型选项
const suggestionTypes = [
  { label: '系统性能', value: 'system' },
  { label: '资源优化', value: 'resource' },
  { label: '接口优化', value: 'api' },
  { label: '数据库优化', value: 'database' }
]

// 优先级选项
const priorityLevels = [
  { label: '高', value: 'high' },
  { label: '中', value: 'medium' },
  { label: '低', value: 'low' }
]

// 状态选项
const suggestionStatus = [
  { label: '待实施', value: 'pending' },
  { label: '实施中', value: 'implementing' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'cancelled' }
]

// 数据列表
const loading = ref(false)
const suggestionList = ref([])
const total = ref(0)

// 概览数据
const overviewData = reactive({
  healthScore: 0,
  performanceScore: 0,
  resourceUsage: 0,
  optimizationEffect: 0
})

// 对话框控制
const detailDialogVisible = ref(false)
const trackDialogVisible = ref(false)
const activeTrackTab = ref('progress')
const currentSuggestion = ref({})
const trackData = reactive({
  activities: [],
  effectAnalysis: []
})

// 图表引用
const performanceChartRef = ref(null)
const resourceChartRef = ref(null)
let performanceChart = null
let resourceChart = null

// 初始化
onMounted(() => {
  loadData()
  loadOverviewData()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getPerformanceSuggestions(queryParams)
    suggestionList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('加载优化建议列表失败:', error)
    ElMessage.error('加载优化建议列表失败')
  } finally {
    loading.value = false
  }
}

// 加载概览数据
const loadOverviewData = async () => {
  try {
    const res = await getPerformanceOptimizationAnalysis()
    Object.assign(overviewData, res.data)
  } catch (error) {
    console.error('加载概览数据失败:', error)
    ElMessage.error('加载概览数据失败')
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  loadData()
}

// 重置操作
const handleReset = () => {
  queryParams.type = undefined
  queryParams.priority = undefined
  queryParams.status = undefined
  handleQuery()
}

// 生成建议
const handleGenerate = async () => {
  try {
    // TODO: 调用生成建议接口
    ElMessage.success('正在生成优化建议，请稍后查看')
  } catch (error) {
    console.error('生成优化建议失败:', error)
    ElMessage.error('生成优化建议失败')
  }
}

// 导出报告
const handleExport = async () => {
  try {
    const res = await exportPerformanceOptimizationReport(queryParams)
    // TODO: 处理文件下载
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出报告失败:', error)
    ElMessage.error('导出报告失败')
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getPerformanceSuggestionDetail(row.id)
    currentSuggestion.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取建议详情失败:', error)
    ElMessage.error('获取建议详情失败')
  }
}

// 应用建议
const handleApply = async (row) => {
  ElMessageBox.confirm(
    '确认要应用该优化建议吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await applyPerformanceSuggestion({ id: row.id })
      ElMessage.success('应用成功')
      loadData()
    } catch (error) {
      console.error('应用优化建议失败:', error)
      ElMessage.error('应用优化建议失败')
    }
  })
}

// 跟踪优化
const handleTrack = async (row) => {
  try {
    const [recordsRes, analysisRes, trendRes] = await Promise.all([
      getPerformanceSuggestionRecords(row.id),
      getPerformanceOptimizationAnalysis({ id: row.id }),
      getPerformanceOptimizationTrend({ id: row.id })
    ])
    
    trackData.activities = recordsRes.data.activities
    trackData.effectAnalysis = analysisRes.data.effectAnalysis
    
    // 初始化图表
    if (performanceChartRef.value && resourceChartRef.value) {
      if (!performanceChart) {
        performanceChart = echarts.init(performanceChartRef.value)
      }
      if (!resourceChart) {
        resourceChart = echarts.init(resourceChartRef.value)
      }
      
      // 设置性能趋势图表
      performanceChart.setOption({
        title: { text: '性能趋势' },
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: trendRes.data.times },
        yAxis: { type: 'value' },
        series: [
          {
            name: '响应时间',
            type: 'line',
            data: trendRes.data.responseTimes
          }
        ]
      })
      
      // 设置资源使用趋势图表
      resourceChart.setOption({
        title: { text: '资源使用趋势' },
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: trendRes.data.times },
        yAxis: { type: 'value' },
        series: [
          {
            name: 'CPU使用率',
            type: 'line',
            data: trendRes.data.cpuUsage
          },
          {
            name: '内存使用率',
            type: 'line',
            data: trendRes.data.memoryUsage
          }
        ]
      })
    }
    
    trackDialogVisible.value = true
    activeTrackTab.value = 'progress'
  } catch (error) {
    console.error('获取优化跟踪数据失败:', error)
    ElMessage.error('获取优化跟踪数据失败')
  }
}

// 删除建议
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认要删除该优化建议吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // TODO: 调用删除接口
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      console.error('删除优化建议失败:', error)
      ElMessage.error('删除优化建议失败')
    }
  })
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  loadData()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  loadData()
}

// 计算属性
const getHealthColor = computed(() => {
  const score = overviewData.healthScore
  if (score >= 90) return '#67C23A'
  if (score >= 70) return '#E6A23C'
  return '#F56C6C'
})

const getPerformanceColor = computed(() => {
  const score = overviewData.performanceScore
  if (score >= 90) return '#67C23A'
  if (score >= 70) return '#E6A23C'
  return '#F56C6C'
})

const getResourceColor = computed(() => {
  const usage = overviewData.resourceUsage
  if (usage <= 70) return '#67C23A'
  if (usage <= 90) return '#E6A23C'
  return '#F56C6C'
})

const getOptimizationColor = computed(() => {
  const effect = overviewData.optimizationEffect
  if (effect >= 20) return '#67C23A'
  if (effect >= 10) return '#E6A23C'
  return '#F56C6C'
})

// 工具方法
const getSuggestionTypeLabel = (type) => {
  const found = suggestionTypes.find(item => item.value === type)
  return found ? found.label : type
}

const getSuggestionTypeTag = (type) => {
  const typeMap = {
    system: '',
    resource: 'success',
    api: 'warning',
    database: 'info'
  }
  return typeMap[type] || 'info'
}

const getPriorityLabel = (priority) => {
  const found = priorityLevels.find(item => item.value === priority)
  return found ? found.label : priority
}

const getPriorityTag = (priority) => {
  const priorityMap = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return priorityMap[priority] || 'info'
}

const getStatusLabel = (status) => {
  const found = suggestionStatus.find(item => item.value === status)
  return found ? found.label : status
}

const getStatusTag = (status) => {
  const statusMap = {
    pending: 'info',
    implementing: 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}
</script>

<style lang="scss" scoped>
.monitor-optimization {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .left {
      display: flex;
      align-items: center;
      gap: 10px;

      h2 {
        margin: 0;
        font-size: 20px;
      }
    }

    .right {
      display: flex;
      gap: 10px;
    }
  }

  .overview-cards {
    margin-bottom: 20px;

    .el-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .health-score,
      .performance-score,
      .resource-usage,
      .optimization-effect {
        text-align: center;
        padding: 20px 0;
      }
    }
  }

  .search-form {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
  }

  .pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }

  .track-content {
    padding: 20px;

    .chart-container {
      margin-bottom: 20px;
    }

    .text-success {
      color: #67C23A;
    }

    .text-danger {
      color: #F56C6C;
    }
  }
}

.ml-2 {
  margin-left: 8px;
}
</style> 